package com.training.web.controller;

import com.training.bean.StageAuthorization;
import com.training.base.Result;
import com.google.gson.Gson;
import com.training.base.ResponseUtils;
import com.training.web.service.WebAuthorizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/web/authorization")
public class WebAuthorizationController {

    @Autowired
    private WebAuthorizationService service;
    
    @Autowired
    private ResponseUtils responseUtils;

    /**
     * 获取所有阶段授权信息（后台管理专用）
     * @return 授权信息列表结果
     */
    @GetMapping("/getAll")
    public ResponseEntity<Result<List<StageAuthorization>>> getAllAuthorizations() {
        try {
            List<StageAuthorization> authorizations = service.getAllAuthorizations();
            return responseUtils.success(authorizations, "获取授权列表成功");
        } catch (Exception e) {
            e.printStackTrace();
            return responseUtils.failWithType(500, "获取授权列表失败: " + e.getMessage());
        }
    }

    /**
     * 添加阶段授权（后台管理专用）
     * @param authorization 授权信息对象
     * @return 添加结果
     */
    @PostMapping("/add")
    public ResponseEntity<Result<StageAuthorization>> addAuthorization(@RequestBody StageAuthorization authorization) {
        try {
            StageAuthorization savedAuthorization = service.addAuthorization(authorization);
            return responseUtils.success(savedAuthorization, "添加授权成功");
        } catch (Exception e) {
            e.printStackTrace();
            return responseUtils.failWithType(500, "添加授权失败: " + e.getMessage());
        }
    }

    /**
     * 更新阶段授权信息（后台管理专用）
     * @param authorization 授权信息对象
     * @return 更新结果
     */
    @PutMapping("/update")
    public ResponseEntity<Result<StageAuthorization>> updateAuthorization(@RequestBody StageAuthorization authorization) {
        try {
            StageAuthorization updatedAuthorization = service.updateAuthorization(authorization);
            return responseUtils.success(updatedAuthorization, "更新授权成功");
        } catch (Exception e) {
            e.printStackTrace();
            return responseUtils.failWithType(500, "更新授权失败: " + e.getMessage());
        }
    }

    /**
     * 删除指定ID的阶段授权（后台管理专用）
     * @param id 授权ID
     * @return 删除结果
     */
    @DeleteMapping("/delete/{id}")
    public ResponseEntity<Result<Object>> deleteAuthorization(@PathVariable int id) {
        try {
            service.deleteAuthorization(id);
            return responseUtils.success(null, "删除授权成功");
        } catch (Exception e) {
            e.printStackTrace();
            return responseUtils.fail(500, "删除授权失败: " + e.getMessage());
        }
    }
}